<template>
  <div class="showDiv">
    <div style="padding: 10px; padding-left: 20px">
      <!-- 搜索框 -->
      <el-form :inline="true" :model="searchProductType" class="demo-form-inline" v-if="showSearch">
        <el-form-item label="分类名称">
          <el-input v-model="searchProductType.itemTypeName" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-select v-model="searchProductType.enableFlag" placeholder="是否启用">
            <el-option label="是" value="Y"></el-option>
            <el-option label="否" value="N"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="checkMdItemTypeCondition">查询</el-button>
          <el-button @click="cleanProduct">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row>
        <el-col :span="22">
          <!-- 按钮 -->
          <el-button icon="el-icon-sort" type="info" size="small" @click="toggleAllRows">展开/折叠</el-button>
        </el-col>
        <el-col :span="2">
          <div>
            <el-tooltip content="隐藏搜索" placement="top">
              <el-button icon="el-icon-search" circle @click="toggleSearch"></el-button>
            </el-tooltip>
            <el-tooltip content="刷新" placement="top">
              <el-button icon="el-icon-refresh" circle @click="refresh"></el-button>
            </el-tooltip>
          </div>
        </el-col>
      </el-row>
    </div>


    <!-- 树形表格 -->
    <transition name="slide-fade">
      <el-table :data="treeData" ref="treeTable" style="width:  100%" row-key="itemTypeId"
        :tree-props="{ children: 'children' }" :default-expand-all="isAllExpanded" :border="true"
        v-show="treeShowTable">
        <el-table-column prop="itemTypeName" sortable label="分类"></el-table-column>
        <el-table-column prop="itemTypeCode" sortable label="产品物料类型编码"></el-table-column>
        <el-table-column prop="itemOrProduct" sortable label="物料/产品"></el-table-column>
        <el-table-column prop="enableFlag" sortable label="是否启用">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.enableFlag === 'Y'">是</el-tag>
            <el-tag v-else type="danger">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" sortable label="创建时间"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-col :span="8">
              <el-link type="primary" @click="openAddDialog(scope.row.itemTypeId)">新增</el-link>
            </el-col>
            <el-col :span="8">
              <el-link type="primary" @click="openChangDialog(scope.row.itemTypeId)">修改</el-link>
            </el-col>
            <el-col :span="8">
              <el-link v-if="scope.row.parentTypeId !== 0" type="primary"
                @click="delProduct(scope.row.itemTypeId)">删除</el-link>
            </el-col>
          </template>
        </el-table-column>
      </el-table>
    </transition>

    <!-- 普通查询固定条件的表格 -->
    <transition name="fade">
      <!-- 普通查询固定条件的表格 -->
      <el-table :data="productAll" style="width:100%" :border="true" v-show="normalShowTable">
        <el-table-column prop="itemTypeName" sortable label="分类"></el-table-column>
        <el-table-column prop="itemTypeCode" sortable label="产品物料类型编码"></el-table-column>
        <el-table-column prop="itemOrProduct" sortable label="物料/产品"></el-table-column>
        <el-table-column prop="enableFlag" sortable label="是否启用">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.enableFlag === 'Y'">是</el-tag>
            <el-tag v-else type="danger">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" sortable label="创建时间"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-col :span="8">
              <el-link type="primary" @click="openAddDialog(scope.row.itemTypeId)">新增</el-link>
            </el-col>
            <el-col :span="8">
              <el-link type="primary" @click="openChangDialog(scope.row.itemTypeId)">修改</el-link>
            </el-col>
            <el-col :span="8">
              <el-link v-if="scope.row.parentTypeId !== 0" type="primary"
                @click="delProduct(scope.row.itemTypeId)">删除</el-link>
            </el-col>
          </template>
        </el-table-column>
      </el-table>
    </transition>

    <!-- dialog部分 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible"  @close="closeDialog">
      <el-form ref="productTypeRef" :rules="rules" :model="productTypeRef">
        <el-row>
          <el-col :span="24">
            <el-form-item label="父分类" v-show="productTypeRef.parentTypeName !== null">
              <el-input v-model="productTypeRef.parentTypeName" autocomplete="off" readonly
                style="width: 575px;"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="itemTypeName">
              <el-input v-model="productTypeRef.itemTypeName" autocomplete="off" style="width: 200px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input v-model="productTypeRef.orderNum" autocomplete="off" style="width: 200px;"></el-input>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="物料/产品" prop="itemOrProduct">
              <el-radio v-model="productTypeRef.itemOrProduct" label="物料">物料</el-radio>
              <el-radio v-model="productTypeRef.itemOrProduct" label="产品">产品</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态" prop="enableFlag">
              <el-radio v-model="productTypeRef.enableFlag" label="Y">是</el-radio>
              <el-radio v-model="productTypeRef.enableFlag" label="N">否</el-radio>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm('productTypeRef')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import qs from 'qs';
export default {
  data() {
    return {
      rules: {
        itemTypeName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ],
        orderNum: [
          { required: true, message: '请输入显示排序', trigger: 'blur' }
        ],
        itemOrProduct: [
          { required: true, message: '请选择物料/产品', trigger: 'change' }
        ],
        enableFlag: [
          { required: true, message: '请选择启用状态', trigger: 'change' }
        ]
      },
      //新增或修改的共用表单
      productTypeRef: {
        parentTypeName: '',
        parentTypeId: '',
        itemTypeName: '',
        orderNum: '',
        itemOrProduct: '',
        enableFlag: '',
      },
      dialogTitle: "",//设置当前的dialog名称
      isAllExpanded: false, // 跟踪当前是否为全部展开状态
      showSearch: true, // 控制搜索框的显示和隐藏
      arrayproduct: [],//后端传递过来的所有数据
      treeData: [], // 存储转换后的树形数据
      searchProductType: {
        enableFlag: '',
        itemTypeName: '',
      },
      treeShowTable: true,//默认显示表格，如果不显示则进行了条件查询
      normalShowTable: false,//普通的表格，只在进行了条件查询进行显示
      productAll: [],
      dialogFormVisible: false,//默认dialog不显示
      itemTypeName: [],
    };
  },
  mounted() {
    this.checkMdItemTypeAll();
  },
  methods: {
    //查询单条的数据，来进行数据的回显
    checkProductById(itemTypeId) {
      this.$axios.post("http://localhost:9970/emsSystem/api/MdItemType/checkProductById/" + itemTypeId).then((res) => {
        this.productTypeRef = res.data.data
      })
    },
    //关闭dialog并且清空里面的数据
    closeDialog() {
      this.dialogFormVisible = false;
      this.$refs.productTypeRef.resetFields();
    },
    //添加打开dialog
    openAddDialog(itemTypeId) {
      this.dialogFormVisible = true;
      this.dialogTitle = "添加分类"
      //将本条的itemTypeId作为添加对象的父id设置进去
      this.productTypeRef.parentTypeId = itemTypeId

    },
    //修改打开dialog
    openChangDialog(itemTypeId) {
      this.dialogFormVisible = true;
      this.dialogTitle = "修改分类"
      //回显查询
      this.checkProductById(itemTypeId);
    },
    //筛选条件，不能添加名称相同的
    checkNameUniqueness(newName) {
      return this.arrayproduct.every(item => item.itemTypeName !== newName);
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addOrChangeProduct();
        } else {
          return false;
        }
      });
    },
    //新增修改数据
    addOrChangeProduct() {
      console.log(this.dialogTitle);
      if (this.dialogTitle === "添加分类") {
        this.productTypeRef.itemTypeId=""
        //序列化
        let qsStr = qs.stringify(this.productTypeRef)
        console.log(qsStr);
        //添加
        //将当前的名称进行判断，看是否重复
        if (this.checkNameUniqueness(this.productTypeRef.itemTypeName)) {
          this.$axios.post("http://localhost:9970/emsSystem/api/MdItemType/addProduct", qsStr).then((res) => {
            if (res.data.code == 200) {
              this.$message.success("新增成功");
              this.dialogFormVisible = false;
              this.checkMdItemTypeAll();
              this.treeShowTable=true;
              this.normalShowTable=false;
            }
          })
        } else {
          this.$message.warning("此分类名称已存在，请选择另一个名称");
        }
      }
      if (this.dialogTitle === "修改分类") {
        //序列化
        let qsStrChang = qs.stringify(this.productTypeRef)
        console.log("xxxxxxxxxxxxxxxx",qsStrChang);
        
        //修改
        this.$axios.post("http://localhost:9970/emsSystem/api/MdItemType/changProduct", qsStrChang).then((res) => {
          if (res.data.code == 200) {
            this.$message.success("修改成功");
            this.dialogFormVisible = false;
            this.checkMdItemTypeAll();
            this.treeShowTable=true;
            this.normalShowTable=false;
          }
        })
      }
    },
    //根据id删除指定数据,但是如果下面有子节点不能进行删除。需要下面没有子节点才能进行删除
    delProduct(itemTypeId) {
      console.log("id", itemTypeId);
      this.$confirm("确定要删除该编号为 " + itemTypeId + " 的信息, 是否继续?", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete("http://localhost:9970/emsSystem/api/MdItemType/delProduct/" + itemTypeId).then((res) => {
          if (res.data.code === 200) {
            console.log(res.data.data);
            if (res.data.data !== 0) {
              //删除成功
              this.$message.success("删除成功");
              //显示树形表
              this.treeShowTable = true;
              this.normalShowTable = false;
            } else {
              //删除失败
              this.$message.error("分类数据不为空，不能删除！！！");
            }
            this.checkMdItemTypeAll();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 全部展开或折叠的方法
    toggleAllRows() {
      this.isAllExpanded = !this.isAllExpanded;
      this.$nextTick(() => {
        if (this.isAllExpanded) {
          this.expandAllRows();
        } else {
          this.collapseAllRows();
        }
      });
    },
    expandAllRows() {
      this.traverseAndToggle(true);
    },
    collapseAllRows() {
      this.traverseAndToggle(false);
    },
    traverseAndToggle(expand) {
      const traverse = (rows) => {
        for (let row of rows) {
          this.$refs.treeTable.toggleRowExpansion(row, expand);
          if (row.children && row.children.length) {
            traverse(row.children);
          }
        }
      };
      traverse(this.treeData);
    },
    //刷新按钮
    refresh() {
      location.reload();
    },
    //是否显示搜索框
    toggleSearch() {
      // 切换搜索框的显示和隐藏
      this.showSearch = !this.showSearch;
    },
    //清除搜索框内容
    cleanProduct() {
      this.searchProductType.enableFlag = "",
        this.searchProductType.itemTypeName = ""
    },
    //条件查询
    checkMdItemTypeCondition() {
      //进行逻辑判定 如果传入的值都为空，那就是显示树形结构的表
      if (this.searchProductType.enableFlag === "" && this.searchProductType.itemTypeName === "") {
        console.log("都为空");
        this.treeShowTable = true;
        this.normalShowTable = false;
        //调用查询全部数据方法
        this.checkMdItemTypeAll();
      } else {
        //如果传递有值那就是要进行特定的数据查询，不需要使用树形结构的表了
        this.treeShowTable = false;
        this.normalShowTable = true;
        let qsStr = qs.stringify(this.searchProductType);
        this.$axios.post("http://localhost:9970/emsSystem/api/MdItemType/checkMdItemTypeCondition", qsStr).then((res) => {
          console.log("查出来的数据", res.data.data);
          this.productAll = res.data.data
        })
      }

    },

    //查询全部数据
    checkMdItemTypeAll() {
      this.$axios.post(`http://localhost:9970/emsSystem/api/MdItemType/CheckMdItemTypeAll`)
        .then((res) => {
          this.arrayproduct = res.data.data;
          console.log("arrayproduct", this.arrayproduct);
          const newTreeData = this.buildTree(this.arrayproduct);
          this.$set(this, 'treeData', newTreeData); // 使用 $set 确保数据响应性
          this.$nextTick(() => {
            console.log("DOM updated");
          });
        })
        .catch((error) => {
          console.error("There was an error fetching the data!", error);
        });
    },
    buildTree(data, parentId = 0) { // 默认根节点的 parentTypeId 是 0

      return (data || []).filter(item => item.parentTypeId === parentId)
        .map(item => ({
          ...item,
          children: item.children ? item.children : this.buildTree(data, item.itemTypeId),
          // hasChildren: this.hasChildren(data, item.itemTypeId)
        }));
    },
    // hasChildren(data, id) {
    //   const result = (data || []).some(item => item.parentTypeId === id);
    //   console.log(`Checking if node ${id} hasChildren:`, result); // 调试信息
    //   return result;
    // },
  }
};
</script>

<style scoped>
.showDiv {
  background-color: white;
  border-radius: 10px;
}

/* 进入和离开动画可以有不同的持续时间和函数 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-to

/* .fade-leave-active in <2.1.8 */
  {
  opacity: 0;
}

.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.8s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateX(20px);
  opacity: 0;
}
</style>